<template>
    <div class="create-lottery-container">
        <div class="page-header">
            <h2>创建抽奖活动</h2>
        </div>

        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="lottery-form">
            <el-form-item label="选择群组" prop="groupId">
                <el-select v-model="form.groupId" placeholder="请选择群组" class="form-input" :loading="groupLoading">
                    <el-option v-for="group in groupList" :key="group.groupId" :label="group.name"
                        :value="group.groupId" />
                </el-select>
            </el-form-item>

            <el-form-item label="活动名称" prop="title">
                <el-input v-model="form.title" placeholder="请输入活动名称" class="form-input" />
            </el-form-item>

            <el-form-item label="奖品" prop="prize">
                <el-input v-model="form.prize" placeholder="请输入奖品名称" class="form-input" />
            </el-form-item>

            <el-form-item label="参与人数" prop="maxParticipants">
                <el-input-number v-model="form.maxParticipants" :min="1" :max="1000" :step="1"
                    class="form-input-number" />
            </el-form-item>

            <el-form-item label="中奖人数" prop="winnerCount">
                <el-input-number v-model="form.winnerCount" :min="1" :max="form.maxParticipants" :step="1"
                    class="form-input-number" />
            </el-form-item>

            <el-form-item label="消耗积分" prop="pointsCost">
                <el-input-number v-model="form.pointsCost" :min="0" :max="1000" :step="1" class="form-input-number" />
            </el-form-item>

            <el-form-item label="开奖方式" prop="drawMode">
                <el-radio-group v-model="form.drawMode">
                    <el-radio :label="'auto'">人满自动开奖</el-radio>
                    <el-radio :label="'time'">定时开奖</el-radio>
                    <el-radio :label="'manual'">手动开奖</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="延迟开奖" v-if="form.drawMode === 'auto'" prop="delaySeconds">
                <el-input-number v-model="form.delaySeconds" :min="0" :max="3600" :step="1" class="form-input-number" />
                <span class="unit-label">秒</span>
                <div class="help-text">人数满后延迟多少秒开奖，设为0则立即开奖</div>
            </el-form-item>

            <el-form-item label="开奖时间" v-if="form.drawMode === 'time'" prop="drawAt">
                <el-date-picker v-model="form.drawAt" type="datetime" placeholder="选择开奖时间" format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate" class="form-input" />
                <div class="help-text">到达设定时间后自动开奖，不受参与人数限制</div>
                <div class="warning-text">
                    <i class="el-icon-warning-outline"></i>
                    注意：设置的开奖时间必须在当前时间之后，建议至少预留10分钟的时间。所选时间过近可能导致定时开奖失效。
                </div>
            </el-form-item>

            <el-form-item label="关注频道要求">
                <el-switch v-model="form.requireChannel" />
            </el-form-item>

            <div v-if="form.requireChannel">
                <el-form-item label="频道链接" prop="channelLink">
                    <el-input v-model="form.channelLink" placeholder="请输入频道链接" class="form-input" />
                    <div class="help-text">格式：https://t.me/频道名 或 @频道名</div>
                </el-form-item>

                <el-form-item label="验证失败处理">
                    <el-radio-group v-model="form.channelVerificationMode">
                        <el-radio :label="'strict'">严格模式（验证失败拒绝参与）</el-radio>
                        <el-radio :label="'lenient'">宽松模式（验证失败仍允许参与）</el-radio>
                    </el-radio-group>
                    <div class="help-text">注意：要使验证正常工作，机器人必须是频道管理员</div>
                </el-form-item>
            </div>

            <el-form-item label="赞助商" prop="sponsor">
                <el-input v-model="form.sponsor" placeholder="请输入赞助商名称" class="form-input" />
            </el-form-item>

            <el-form-item label="联系方式" prop="sponsorContact">
                <el-input v-model="form.sponsorContact" placeholder="例如：@username" class="form-input" />
            </el-form-item>

            <el-form-item label="领奖说明" prop="rewardInfo">
                <el-input v-model="form.rewardInfo" placeholder="例如：领奖请联系群主" class="form-input" />
                <div class="help-text">自定义领奖说明文本，说明中奖者如何领取奖品</div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm" :loading="submitting">创建活动</el-button>
                <el-button @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getGroups } from '../../../api/group';
import { createLottery } from '../../../api/lottery';

export default {
    name: 'CreateLottery',
    setup() {
        const router = useRouter();
        const formRef = ref(null);
        const submitting = ref(false);
        const groupList = ref([]);
        const groupLoading = ref(false);

        // 表单数据
        const form = reactive({
            groupId: '',
            title: '抽奖活动',
            prize: '',
            maxParticipants: 10,
            winnerCount: 1,
            pointsCost: 1,
            requireChannel: true,
            channelLink: 'https://t.me/aaaaaa',
            channelVerificationMode: 'lenient',
            sponsor: '小宇科技',
            sponsorContact: '@codevip66',
            rewardInfo: '领取奖品请联系本群管理员',
            drawMode: 'auto',
            delaySeconds: 10,
            drawAt: null
        });

        // 表单验证规则
        const rules = {
            groupId: [{ required: true, message: '请选择群组', trigger: 'change' }],
            title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
            prize: [{ required: true, message: '请输入奖品名称', trigger: 'blur' }],
            maxParticipants: [{ required: true, message: '请设置参与人数', trigger: 'blur' }],
            winnerCount: [{ required: true, message: '请设置中奖人数', trigger: 'blur' }],
            pointsCost: [{ required: true, message: '请设置消耗积分', trigger: 'blur' }],
            drawAt: [
                {
                    required: true,
                    message: '请选择开奖时间',
                    trigger: 'change',
                    validator: (rule, value, callback) => {
                        if (form.drawMode === 'time' && !value) {
                            callback(new Error('请选择开奖时间'));
                        } else {
                            callback();
                        }
                    }
                }
            ],
            channelLink: [
                {
                    required: true,
                    message: '请输入频道链接',
                    trigger: 'blur',
                    validator: (rule, value, callback) => {
                        if (form.requireChannel && !value) {
                            callback(new Error('请输入频道链接'));
                        } else {
                            callback();
                        }
                    }
                }
            ]
        };

        // 获取群组列表
        const fetchGroups = async () => {
            groupLoading.value = true;
            try {
                console.log('开始获取群组列表...');
                const res = await getGroups();
                console.log('获取到的群组数据:', res);

                if (res.data.success) {
                    // 确保返回的数据格式正确
                    groupList.value = res.data.data.map(group => ({
                        groupId: group.groupId,
                        name: group.name || `群组${group.groupId}`  // 使用name字段
                    }));
                    console.log('处理后的群组列表:', groupList.value);
                } else {
                    console.error('获取群组列表失败:', res.data.message);
                    ElMessage.error('获取群组列表失败');
                }
            } catch (error) {
                console.error('获取群组列表出错:', error);
                ElMessage.error('获取群组列表失败');
            } finally {
                groupLoading.value = false;
            }
        };

        // 提交表单
        const submitForm = async () => {
            if (!formRef.value) return;

            await formRef.value.validate(async (valid) => {
                if (!valid) return;

                submitting.value = true;

                try {
                    // 准备提交的数据
                    const submitData = {
                        groupId: form.groupId,
                        title: form.title,
                        prize: form.prize,
                        maxParticipants: form.maxParticipants,
                        winnerCount: form.winnerCount,
                        pointsCost: form.pointsCost,
                        requireChannel: form.requireChannel,
                        channelLink: form.channelLink,
                        channelVerificationMode: form.channelVerificationMode,
                        sponsor: form.sponsor,
                        sponsorContact: form.sponsorContact,
                        rewardInfo: form.rewardInfo,
                        drawMode: form.drawMode
                    };

                    // 根据开奖方式添加相关字段
                    if (form.drawMode === 'auto') {
                        submitData.delaySeconds = form.delaySeconds;
                        console.log('创建自动开奖抽奖活动，延迟秒数:', form.delaySeconds);
                    } else if (form.drawMode === 'time') {
                        submitData.drawAt = form.drawAt;
                        console.log('创建定时开奖抽奖活动，开奖时间:', form.drawAt);
                    } else {
                        console.log('创建手动开奖抽奖活动');
                    }

                    const res = await createLottery(submitData);

                    if (res.data.success) {
                        ElMessage.success('抽奖活动创建成功');
                        router.push('/admin/points/lottery');
                    } else {
                        ElMessage.error(res.data.message || '创建失败');
                    }
                } catch (error) {
                    console.error('创建抽奖活动失败:', error);
                    ElMessage.error('创建抽奖活动失败');
                } finally {
                    submitting.value = false;
                }
            });
        };

        // 返回列表页
        const goBack = () => {
            router.push('/admin/points/lottery');
        };

        const disabledDate = (time) => {
            // 禁用今天之前的日期和当前时间10分钟内的时间
            const minTime = Date.now() + 10 * 60 * 1000; // 当前时间+10分钟
            return time.getTime() < minTime;
        };

        onMounted(() => {
            console.log('组件已挂载，开始获取群组列表');
            fetchGroups();
        });

        return {
            formRef,
            form,
            rules,
            submitting,
            groupList,
            groupLoading,
            submitForm,
            goBack,
            disabledDate
        };
    }
};
</script>

<style scoped>
.create-lottery-container {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
}

.lottery-form {
    max-width: 700px;
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-input {
    width: 100%;
}

.form-input-number {
    width: 200px;
}

.unit-label {
    margin-left: 10px;
    color: #606266;
}

.help-text {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
}

.warning-text {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
}
</style>